/**
 * FansUnion Page Library v1.1.4
 * LastUpdate:2015-3-31
 * Copyright 2012~2112, xiaolei
 * QQ: 240370818
 * Email:fansunion@qq.com
 *
 */

/**
 * 分页组件，可以作为自定义内容或者标准型表格的分页，比如文章评论，user列表。 表格分页，模版由外界传入。
 * <br/>提供给用户的构造表格的方法主要有2个：构造方法 new FuPage(options)和发送数据请求send(params)。
 * 事件通知方法有：onfilled,onedited,onerror(暂时没有)
 */
function FuPage(options) {
	this.url = options.url;
	this.params = options.params;

	this.startNo = 1;
	this.endNo = 1;
	// 默认是table
	if (options.isTable == undefined) {
		this.isTable = true;
	} else {
		this.isTable = options.isTable;
	}
	this.template = options.template;
	this.bodyHolder = options.bodyHolder;
	this.pageHolder = options.pageHolder;
	if (options.loadingImageUrl) {
		this.loadingImageUrl = loadingImageUrl;
	}
	if (!this.loadingImageUrl) {
		this.loadingImageUrl = $("#loadingImageUrl").val();
	}
}
FuPage.prototype.over = function(url,params,data){
	
};
// 向后端发送请求
FuPage.prototype.send = function(params) {
	var that = this;
	if (typeof params == 'object') {
		$.each(params, function(p, val) {
			that.params[p] = val;
		})
	}
	loadingAnimation(this.bodyHolder, this.loadingImageUrl, this.isTable);
	// console.log("FuPage params:" + that.params);
	var renderOk = false;
	var timeout = false;
	post(that.url, that.params, function(data) {
		if (data.code == -1) {
			tip(that.bodyHolder, that.isTable, "会话已超时，请重新登录...");
			timeout = true;
			return;
		}
		var page = data.page;
		if (!page) {
			// console.error("page is null,data is "+data);
			data = $.parseJSON(data);
			page = data.page;
		}
		that.renderTable(page);
		renderPage(that, page);
		addPageEvent(that, page);
		that.over(that.url,that.params,data);
		renderOk = true;
	});
	setTimeout(function() {
		if (!renderOk && !timeout) {
			busyTip(that.bodyHolder, that.isTable);
		}
	}, 5000);
}

// 居中对齐，展示动画效果
function loadingAnimation(bodyHolder, loadingImageUrl, isTable) {
	console.log("fupage-loading...");
	var loadingText = "玩命加载中...";
	var loadingImage = "<img src='" + loadingImageUrl
			+ "' alt='玩命加载中...' title='玩命加载中...' />";
	var loadingDiv = null;
	// 表格才加“<tr>”
	if (isTable) {
		// 偷懒，一般表格不会超过20列，设置为20，横跨所有列
		loadingDiv = "<tr style='text-align:center;'><td colspan=20>";
	} else {
		loadingDiv = "<div style='text-align:center;' >"
	}
	if (loadingImageUrl) {
		loadingDiv += loadingImage;
	} else {
		loadingDiv += loadingDiv;
	}
	if (isTable) {
		loadingDiv += '</td></tr>';
	} else {
		loadingDiv += "</div>";
	}
	console.log(loadingDiv);
	$("#" + bodyHolder).html(loadingDiv);
}

function busyTip(bodyHolder, isTable) {
	var busyTipDiv = null;
	// 表格才加“<tr>”
	if (isTable) {
		// 偷懒，一般表格不会超过20列，设置为20，横跨所有列
		busyTipDiv = "<tr style='text-align:center;'><td colspan=20>";
	} else {
		busyTipDiv = "<div style='text-align:center;' >"
	}

	busyTipDiv += "服务器繁忙，请稍后再试...";

	if (isTable) {
		busyTipDiv += '</td></tr>';
	} else {
		busyTipDiv += "</div>";
	}
	console.log("busyTip:" + busyTipDiv);
	$("#" + bodyHolder).html(busyTipDiv);
}

function tip(bodyHolder, isTable, tip) {
	var busyTipDiv = null;
	// 表格才加“<tr>”
	if (isTable) {
		// 偷懒，一般表格不会超过20列，设置为20，横跨所有列
		busyTipDiv = "<tr style='text-align:center;'><td colspan=20>";
	} else {
		busyTipDiv = "<div style='text-align:center;' >"
	}

	busyTipDiv += tip;

	if (isTable) {
		busyTipDiv += '</td></tr>';
	} else {
		busyTipDiv += "</div>";
	}
	console.log("tip:" + busyTipDiv);
	$("#" + bodyHolder).html(busyTipDiv);
}
// 渲染表格主体
FuPage.prototype.renderTable = function(page) {
	// var ok = this.isTable && this.template != null;
	if (!this.template) {
		console.error("template is null");
		return false;
	}
	var rows = page.rows || page.list;
	if (!rows) {
		var content = '没有查询到任何数据';
		tip(this.bodyHolder,this.isTable,content);
		return;
	}
	
	var divs = '';
	for (var i = 0; i < rows.length; i++) {
		var row = rows[i]
		// 解析变量表达式{}
		var pageReg = /\{([^}]+)\}/g;
		var div = this.template.replace(pageReg, function() {
			// console.log("0:"+arguments[0]);
			// console.log("1:"+arguments[1]);
			// console.log("2:"+arguments[2]);
			// console.log("3:"+arguments[3]);
			// console.log(arguments[1]);
			var exp = "row." + arguments[1];
			var tdValue = "";
			try {
				tdValue = eval(exp);
			} catch (e) {
				//				
			}
			// console.log(tdValue);
			tdValue = nullToEmpty(tdValue);
			return tdValue;
		});
		// 解析@标记的函数
		var trReg = /@([^(]+)\(([^)]*)\)|\{([^}]+)\}|(\[\])/g;
		div = div.replace(trReg, function(full, funName, funArgs) {
			// 0:@centToYuan(120000)
			// 1:centToYuan
			// 2:120000,1
			// console.log("0:"+arguments[0]);
			// console.log("1:"+arguments[1]);
			// console.log("2:"+arguments[2]);
			// 去掉最后1个逗号“,”,比如“a,b,”
			if (funArgs != null
					&& funArgs.lastIndexOf(",") == funArgs.length - 1) {
				// console.log("find , :"+funArgs);
				funArgs = funArgs.substr(0, funArgs.length - 1);
			}
			// 第1个“,”前，+空
			// console.log(funArgs+",funArgs:"+funArgs.indexOf(","));
			var a = "";
			if (funArgs != null && funArgs.indexOf(",") == 0) {
				// console.log("find , :"+funArgs);
				funArgs = "''" + funArgs;
			}
			var fn = funName + "(" + funArgs + ")";
			var tdValue = "";
			try {
				tdValue = eval(fn);

			} catch (e) {
				// e
			}
			// null undefined转化为空
			tdValue = nullToEmpty(tdValue);
			return tdValue;
		});
		divs += div;
	}
	$("#" + this.bodyHolder).html(divs);
}

// 未定义的变量，用""展示
var nullToEmpty = function(value) {
	if (value == null || value == undefined) {
		value = "";
	}
	return value;
}
// 渲染分页栏
function renderPage(fuPage, page) {
	var pageDiv = buildPage(fuPage, page);
	$("#" + fuPage.pageHolder).html(pageDiv);
}

// 为分页超链接绑定click事件
function addPageEvent(fuPage, page) {
	// 解决同一个页面，多个实例导致ID冲突的问题
	var prefix = fuPage.pageHolder;
	var nextPageA = document.getElementById(prefix + "nextPageA");
	if (nextPageA != null) {
		nextPageA.onclick = function() {
			goToPage(fuPage, fuPage.params.pageNo + 1)
		};
	}
	var prevPageA = document.getElementById(prefix + "prevPageA");
	if (prevPageA != null) {
		prevPageA.onclick = function() {
			goToPage(fuPage, fuPage.params.pageNo - 1)
		}
	}
	var beginPageA = document.getElementById(prefix + "beginPageA");
	if (beginPageA) {
		beginPageA.onclick = function() {
			goToPage(fuPage, 1);
		}
	}
	var endPageA = document.getElementById(prefix + "endPageA");
	if (endPageA != null) {
		endPageA.onclick = function() {
			goToPage(fuPage, page.totalPage)
		}
	}
	for (var no = fuPage.startNo; no <= fuPage.endNo; no++) {
		var id = prefix + "noPageA" + no;
		// console.log(id);
		var noPageA = document.getElementById(id);
		if (noPageA != null && no != fuPage.pageNo) {
			$("#" + id).on("click", function(e) {
				// 找到事件源，事件源的文本内容"1"即为页数，string转换成int，防止str+int结果是string
				var number = $(this).text();
				// 把string转换成int类型
				number = new Number(number);

				goToPage(fuPage, number)
			});
		}
	}
}

// 加载指定的页面
function goToPage(fuPage, no) {
	fuPage.params.pageNo = no;
	fuPage.send();
}

// 构造分页栏的html，记得给第“1”页等按钮，绑定事件
function buildPage(fuPage, page) {
	var totalPage = page.totalPage;
	var pageNo = page.pageNo || 1;
	var pageSize = page.pageSize;
	var totalCount = page.totalCount;
	if (totalCount <= 0) {
		console.log("totalCount=0")
		return "";
	}
	// 半距离算法
	var half = 5;
	var startNo = 1;
	var endNo = totalPage;
	var left = pageNo - half;
	var right = pageNo + half;
	if (left < 1) {
		startNo = 1;
	} else {
		startNo = left;
	}
	if (right > totalPage) {
		endNo = totalPage;
	} else {
		endNo = right;
	}
	fuPage.startNo = startNo;
	fuPage.endNo = endNo;
	var prefix = fuPage.pageHolder;
	// 分页链接，绑定事件
	var ul = '<ul class="pagination">';
	if (pageNo == 1) {
		ul += '<li class="disabled"><span>首页</span></li><li><span>上一页</span></li>';
	} else {
		ul += '<li><a href="javascript:;" id="' + prefix
				+ 'beginPageA">首页</a></li><li><a href="javascript:;" id="'
				+ prefix + 'prevPageA">上一页</a></li>';
	}
	for (var no = startNo; no <= endNo; no++) {
		if (no == pageNo) {
			ul += '<li class="active"><a href="javascript:;">' + no
					+ '</a></li>';
		} else {
			ul += '<li><a href="javascript:;" id="' + prefix + 'noPageA' + no
					+ '" >' + no + '</a></li>';
		}
	}

	if (pageNo == totalPage)
		ul += '<li class="disabled"><span>下一页</span></li><li class="disabled"><span>尾页</span></li>';
	else {
		ul += '<li><a href="javascript:;" id="' + prefix
				+ 'nextPageA" >下一页</a></li><li><a href="javascript:;" id="'
				+ prefix + 'endPageA">尾页</a></li>';
	}
	ul += '<li><span>共' + totalPage + '页</span></li><li><span>共' + totalCount
			+ '条</span></li></ul>';
	return ul;
}
